package com.mall.ums.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.model.domain.ums.Menu;
import com.mall.model.domain.vo.MenuVo;
import com.mall.ums.mapper.MenuMapper;
import com.mall.ums.service.MenuService;
import com.mall.utils.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author clutchcitylee
 * @create 2023-03-12-16:10
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    @Override
    public PageResult listByParentId(Integer parentId, Integer pageNum, Integer pageSize) {
        Page<Menu> menuPage = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getParentId, parentId);
        Page<Menu> page = this.page(menuPage, queryWrapper);
        return PageResult.init(page);
    }

    @Override
    public List<MenuVo> treeList() {
        List<Menu> menuList = this.list();
        List<MenuVo> menuVos = new ArrayList<>();
        for (Menu menu : menuList) {
            LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Menu::getParentId, menu.getId());
            List<Menu> childrenList = this.list(queryWrapper);
            if (childrenList != null && childrenList.size() > 0) {
                MenuVo menuVo = new MenuVo();
                BeanUtils.copyProperties(menu, menuVo);
                List<MenuVo> children = childrenList.stream().map(item -> {
                    MenuVo childrenVo = new MenuVo();
                    BeanUtils.copyProperties(item, childrenVo);
                    return childrenVo;
                }).collect(Collectors.toList());
                menuVo.setChildren(children);
                menuVos.add(menuVo);
            }
        }
        return menuVos;
    }

    @Override
    public void updateHidden(Integer id, Integer hidden) {
        Menu menu = this.getById(id);
        menu.setHidden(hidden);
        this.updateById(menu);
    }
}
